'use strict';
const dbHelper = require("db-helper")
const orderHelper = require("order-helper")
const payUtil = require("pay-util")
const db = uniCloud.database()

exports.main = async (event, context) => {
	console.log('处理支付通知 : ', event)
	let t = event.path.substring(1).split("_");
	let provider = "wxpay" //t[0];
	let platform = "mp-weixin" //t[1];
	let uniPayInstance = payUtil.getPayInstance(provider, platform);
	try {
		let verifyResult = await uniPayInstance.verifyPaymentNotify(event)
		console.log("支付结果", verifyResult)
		if (!verifyResult) {
			return {}
		}
		let {
			outTradeNo,
			totalFee,
			transactionId,
			resultCode
		} = verifyResult

		var order = await dbHelper.getById("t3ds-order", outTradeNo)
		if (!order) {
			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				statusCode: 200,
				body: {
					code: 'SUCCESS',
					message: '成功'
				}
			}
		}
		console.log(`订单状态${order.status}`)
		if (totalFee === order.payment_fee && (resultCode === 'SUCCESS' || resultCode === 'FINISHED')) {
			console.log('---------update order-------')
			await orderHelper.handleOrderPaid(outTradeNo, Date.now())
			order = await dbHelper.getById("t3ds-order", outTradeNo)
			console.log(`订单更新完成，状态：${order.status}`)
			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				statusCode: 200,
				body: {
					code: 'SUCCESS',
					message: '成功'
				}
			}
		} else {
			console.warn('订单未更新，支付数据似乎与订单数据不一致')
		}
		return {};
	} catch (e) {
		console.log("查询支付状态遇到错误", e)
		return {}
	}
};
